package psrc.bd.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import psrc.logic.util.beans.RedeBean;

public class RedeDAO extends AbstractDAO {

	public RedeDAO(Connection conn) {
		super(conn);
	}

	@Override
	public <T> void adiciona(T _bean) throws SQLException {
		RedeBean bean = (RedeBean) _bean;
		String sql = "insert into Rede "
				+ "(nome, responsavel, telefone) values (?, ?, ?)";
		
			PreparedStatement stmt = connection.prepareStatement(sql);

			stmt.setString(1, bean.getNome());
			stmt.setString(2, bean.getResponsavel());
			stmt.setString(3, bean.getTelefone());
			
			stmt.execute();
			stmt.close();

	}

	@Override
	public <T> void remove(T _bean) throws SQLException{
		RedeBean bean = (RedeBean) _bean;
			PreparedStatement stmt = connection.prepareStatement("delete from Rede where id_rede=?");

			stmt.setInt(1, Integer.parseInt(bean.getIdRede()));

			stmt.execute();
			stmt.close();

	}

	@Override
	public <T> void edita(T _bean) throws SQLException{
		RedeBean bean = (RedeBean) _bean;

		String sql = "update Rede set " +"nome=?, responsavel=?, telefone=? where rede=?";
			PreparedStatement stmt = connection.prepareStatement(sql);

			stmt.setString(1, bean.getNome());
			stmt.setString(2, bean.getResponsavel());
			stmt.setString(3, bean.getTelefone());
			stmt.setInt(4, Integer.parseInt(bean.getIdRede()));
			stmt.execute();
			stmt.close();
	}

	@Override
	public <T> List<T> seleciona() throws SQLException{
		List<RedeBean> redes = new ArrayList<RedeBean>();

			PreparedStatement stmt = connection.prepareStatement("select * from Rede");
			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				RedeBean bean = new RedeBean();
				bean.setNome(rs.getString("nome"));
				bean.setResponsavel(rs.getString("responsavel"));
				bean.setTelefone(rs.getString("telefone"));
				bean.setIdRede(rs.getString("id_rede"));

				redes.add(bean);
			}
			rs.close();
			stmt.close();
			return (List<T>) redes;
	}

@Override
	public <T> List<T> selecionaPorId(T param) throws SQLException {
		List<RedeBean> redes = new ArrayList<RedeBean>();
		RedeBean user = (RedeBean) param;
		try {
			PreparedStatement stmt = connection
					.prepareStatement("select * from Rede where id_rede=?");
			stmt.setString(1, user.getIdRede());
			ResultSet rs = stmt.executeQuery();
			
			while (rs.next()) {
				RedeBean bean = new RedeBean();
				bean.setNome(rs.getString("nome"));
				bean.setResponsavel(rs.getString("responsavel"));
				bean.setTelefone(rs.getString("telefone"));
				bean.setIdRede(rs.getString("id_rede"));

				redes.add(bean);
			}
			rs.close();
			stmt.close();
			return (List<T>) redes;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
	}
}
